package cc.shacocloud.mirage.maven.plugin;

import org.jetbrains.annotations.NotNull;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 计算 {@link JarEntryWriter} size 的{@link JarEntryWriter}
 *
 * @author 思追(shaco)
 */
public class CalculateSizeJarEntryWriter implements JarEntryWriter {
    
    private final byte[] bytes;
    
    private final int size;
    
    public CalculateSizeJarEntryWriter(@NotNull JarEntryWriter entryWriter) throws IOException {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            entryWriter.write(outputStream);
            
            this.bytes = outputStream.toByteArray();
            this.size = outputStream.size();
        }
    }
    
    @Override
    public void write(OutputStream outputStream) throws IOException {
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
            inputStream.transferTo(outputStream);
            outputStream.flush();
        }
    }
    
    @Override
    public int size() {
        return size;
    }
}
